import { User } from '../model/User.js'
import { Op } from 'sequelize';

async function userAll(ctx) {

    let keyword = ctx.request.query.keyword
    console.log(keyword);
    let users;

    if (keyword) {
        users = await User.findAll({
            where: {
                [Op.or]: {
                    uname: {
                        [Op.like]: `%${keyword}%`
                    },
                    uage: {
                        [Op.like]: `%${keyword}%`
                    }
                }
            }
        })
    } else {
        users = await User.findAll()
    }

    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: users
    }
}

async function userById(ctx) {
    let id = ctx.params.id
    console.log("查询单个用户  ", id);
    let user = await User.findByPk(id)
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: user
    }
}

async function delById(ctx) {
    let id = ctx.params.id
    console.log("删除用户", id);
    await User.destroy({ where: { id } })
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: null
    }
}

async function addUser(ctx) {
    let obj = ctx.request.body
    console.log("新增用户", obj);

    await User.create(obj)
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: null
    }
}

async function editUser(ctx) {
    let id = ctx.params.id
    let obj = ctx.request.body
    await User.update(obj, { where: { id } })
    console.log("修改用户", obj);
    ctx.body = {
        code: 200,
        msg: "请求成功",
        data: null
    }
}

export const users = [
    { method: "get", path: "/users", fn: userAll },
    { method: "get", path: "/user/:id", fn: userById },
    { method: "delete", path: "/user/:id", fn: delById },
    { method: "post", path: "/user", fn: addUser },
    { method: "put", path: "/user/:id", fn: editUser },
]